/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.expert.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.service.BaseService;
import com.chlitina.store.common.utils.DateUtils;
import com.chlitina.store.modules.base.entity.StoreCare;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.expert.dao.CustomerSolutionDao;
import com.chlitina.store.modules.expert.entity.CustomerSolution;
import com.chlitina.store.modules.expert.entity.CustomerSolutionAndCare;
import com.chlitina.store.modules.expert.entity.CustomerSolutionAndProduct;
import com.chlitina.store.modules.expert.entity.CustomerSolutionExport;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;

/**
 * 客户采纳方案Service
 * @author lvbo
 * @version 2013-06-20
 */
@Component
@Transactional(readOnly = true)
public class CustomerSolutionService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(CustomerSolutionService.class);
	
	@Autowired
	private CustomerSolutionDao customerSolutionDao;
	
	public CustomerSolution get(Long id) {
		return customerSolutionDao.findOne(id);
	}
	
	public List<CustomerSolution> getByStore(Long storeId, int status) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store.id", storeId));
		dc.add(Restrictions.eq("status", status));
		dc.addOrder(Order.asc("id"));
		return customerSolutionDao.find(dc);
	}
	
	public List<CustomerSolution> findByCustomerExam(Long customerExamId){
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.add(Restrictions.eq("customerExam.id", customerExamId));
		return customerSolutionDao.find(dc);
	}
	
	public Page<CustomerSolution> find(Page<CustomerSolution> page, Long customerExamId) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		if (customerExamId != null) {
			dc.add(Restrictions.eq("customerExam.id", customerExamId));
			dc.addOrder(Order.asc("id"));
			return customerSolutionDao.find(page, dc);
		}
		return page;
	}
	
	public Page<CustomerSolution> find(Page<CustomerSolution> page,
			String customerName, Integer statusInt) {
		page.setPageSize(Integer.parseInt(Global.getConfig("page.longPageSize")));
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		dc.createAlias("a.customer", "c");
		if (StringUtils.isNotEmpty(customerName)){
			dc.add(Restrictions.like("c.name", customerName, MatchMode.ANYWHERE));
		}
		if (statusInt != null){
			dc.add(Restrictions.eq("status", statusInt));
		}
		dc.addOrder(Order.asc("id"));
		return customerSolutionDao.find(page, dc);
	}
	
	public List<CustomerSolutionExport> export(Store store, String customerName, Integer statusInt) {
		customerSolutionDao.clear();
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", store));
		dc.createAlias("a.customer", "c");
		if (StringUtils.isNotEmpty(customerName)){
			dc.add(Restrictions.like("c.name", customerName, MatchMode.ANYWHERE));
		}
		if (statusInt != null){
			dc.add(Restrictions.eq("status", statusInt));
		}
		dc.addOrder(Order.asc("id"));
		List<CustomerSolutionExport> cseList = Lists.newArrayList();
		List<CustomerSolution> list = customerSolutionDao.find(dc);
		for (CustomerSolution cs : list) {
			CustomerSolutionExport cse = new CustomerSolutionExport();
			cse.setCustomerName(cs.getCustomerExam().getCustomer().getName());
			cse.setCustomerMobile(cs.getCustomerExam().getCustomer().getMobile());
			cse.setEmployeeName(cs.getCustomerExam().getEmployee().getName());
			cse.setBeginDate(cs.getStart_date());
			cse.setSolutionName(cs.getSolutionFace().getName());
			List<CustomerSolutionAndProduct> productLists = cs.getProductList();
			String productStr = "";
			for (CustomerSolutionAndProduct csap : productLists) {
				//产品xxx(数量：1)
				String name = "";
				StoreProduct storeProduct = csap.getStoreProduct();
				if(storeProduct.getProduct_type() == StoreProduct.TYPE_SYS) {
					name = storeProduct.getProduct().getName();
				} else {
					name = storeProduct.getStoreSelfProduct().getName();
				}
				productStr += name + "(数量：" +csap.getAmount() + ")\n";
			}
			cse.setProducts(productStr);
			List<CustomerSolutionAndCare> careList = cs.getCareList();
			String careStr = "";
			for (CustomerSolutionAndCare csac : careList) {
				//护理xxx
				String name = "";
				StoreCare storeCare = csac.getStoreCare();
				if(storeCare.getCare_type() == StoreCare.TYPE_SYS) {
					name = storeCare.getCare().getName();
				} else {
					name = storeCare.getStoreSelfCare().getName();
				}
				careStr += name + "\n";
			}
			cse.setCares(careStr);
			cseList.add(cse);
		}
		return cseList;
	}
	
	@Transactional(readOnly = false)
	public void save(CustomerSolution customerSolution) {
		customerSolutionDao.save(customerSolution);
	}
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		customerSolutionDao.delete(id);
	}
	
	/**
	 * 查找指定时间内新开单的方案
	 * @param store
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public List<CustomerSolution> findNewTaskCustomerSolution(Store store,
			Date beginDate, Date endDate) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.createAlias("a.employee", "e");
		if (store != null) {
			dc.add(Restrictions.eq("a.store", store));
		}
		Date begin = null;
		if (beginDate != null) {
			begin = DateUtils.getBeginOfDay(beginDate);
		}
		Date end = null;
		if (endDate != null) {
			end = DateUtils.getEndOfDay(endDate);
		}
		if (begin != null && end != null) {
			dc.add(Restrictions.between("a.exam_time", begin, end));
		}
		dc.add(Restrictions.eq("status", CustomerSolution.PROCEED_STATUS));
		return customerSolutionDao.find(dc);
	}
	/**
	 * 查找指定时间内正常结束的方案
	 * @param store
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public List<CustomerSolution> findEndCustomerSolution(Store store,
			Date beginDate, Date endDate) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		if (store != null) {
			dc.add(Restrictions.eq("a.store", store));
		}
		Date begin = null;
		if (beginDate != null) {
			begin = DateUtils.getBeginOfDay(beginDate);
		}
		Date end = null;
		if (endDate != null) {
			end = DateUtils.getEndOfDay(endDate);
		}
		if (begin != null && end != null) {
			dc.add(Restrictions.between("real_end_date", begin, end));
		}
		dc.add(Restrictions.eq("status", CustomerSolution.END_STATUS));
		return customerSolutionDao.find(dc);
	}
	/**
	 * 查找指定时间内提前结束的方案
	 * @param store
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public List<CustomerSolution> findStopCustomerSolution(Store store,
			Date beginDate, Date endDate) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		if (store != null) {
			dc.add(Restrictions.eq("a.store", store));
		}
		Date begin = null;
		if (beginDate != null) {
			begin = DateUtils.getBeginOfDay(beginDate);
		}
		Date end = null;
		if (endDate != null) {
			end = DateUtils.getEndOfDay(endDate);
		}
		if (begin != null && end != null) {
			dc.add(Restrictions.between("real_end_date", begin, end));
		}
		dc.add(Restrictions.eq("status", CustomerSolution.STOP_STATUS));
		return customerSolutionDao.find(dc);
	}
	/**
	 * 查找指定时间内所有的方案
	 * @param store
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public List<CustomerSolution> findAllCustomerSolution(Store store,
			Date beginDate, Date endDate) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		Date begin = null;
		if (beginDate != null) {
			begin = DateUtils.getBeginOfDay(beginDate);
		}
		Date end = null;
		if (endDate != null) {
			end = DateUtils.getEndOfDay(endDate);
		}
		if (begin != null && end != null) {
			//新开单
			Criterion newTaskTime = Restrictions.between("a.exam_time", begin, end);
			SimpleExpression newTaskStatus = Restrictions.eq("status", CustomerSolution.PROCEED_STATUS);
			LogicalExpression first = Restrictions.and(newTaskTime, newTaskStatus);
			//已经结束
			Criterion endTaskTime = Restrictions.between("real_end_date", begin, end);
			Criterion endTaskStatus = Restrictions.in("status", new Object[]{1,2});
			LogicalExpression second = Restrictions.and(endTaskTime, endTaskStatus);
			//组合
			LogicalExpression last = Restrictions.or(first, second);
			dc.add(last);
		}
		return customerSolutionDao.find(dc);
	}
	
	//获取当前记录排第几位
	public int getIndexById(Long currentId, Long customerExamId) {
		DetachedCriteria dc = customerSolutionDao.createDetachedCriteria();
		dc.add(Restrictions.le("id", currentId));
		dc.createAlias("customerExam", "a");
		dc.add(Restrictions.eq("a.store", StoreUtils.getStore()));
		if(customerExamId !=null) {
			dc.add(Restrictions.eq("customerExam.id", customerExamId));
		}
		dc.addOrder(Order.asc("id"));
		return (int)customerSolutionDao.count(dc);
	}
}
